package com.example.api.mall.controller;

import com.example.api.mall.logic.IUserLogic;
import com.example.common.core.annotation.NoLoginAuth;
import com.example.common.core.result.Result;
import com.example.api.mall.utils.TokenUtils;
import com.example.entity.domain.user.User;
import com.example.entity.api.mall.user.InfoVo;
import com.example.entity.api.mall.user.LoginVo;
import com.example.entity.api.mall.user.RegisterVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/user")
//@CrossOrigin
public class UserController {

    @Autowired
    private IUserLogic userLogic;

    @PostMapping("/register")
    @NoLoginAuth
    public Result<Boolean> register(@RequestBody RegisterVo registerVo, HttpServletRequest request){
        boolean res = userLogic.register(registerVo, request);
        return Result.success(res);
    }

    /**
     * TODO @Validated 不起作用
     * @param loginVo
     * @param request
     * @return
     */
    @PostMapping("/login")
    @NoLoginAuth
    public Result<String> login(@RequestBody @Validated LoginVo loginVo, HttpServletRequest request){
        User user = userLogic.login(loginVo, request);
        String token = TokenUtils.createToken(user);
        return Result.success(token);
    }

    @PostMapping("/info")
    public Result<User> info(@RequestBody InfoVo infoVo){
        return Result.success(userLogic.info(infoVo.getUserId()));
    }

}
